package code.google.jcontainer.test.countconsuming;

import code.google.jcontainer.resolver.ClassAnnotationResolver;
import code.google.jcontainer.resolver.ClassResolveContext;
import code.google.jcontainer.resolver.MethodResolveContext;
import code.google.jcontainer.resolver.ResolverException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Consume time for executing a method, can realize by using ThreadLocal or MethodResolveContext.usrDatas
 *
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 * @create 2009-12-22 17:30:50
 */
public class CountConsumingAnnotationResolver implements ClassAnnotationResolver {

    private static final Log log = LogFactory.getLog(CountConsumingAnnotationResolver.class);
/*
    private final static ThreadLocal<Long> tl = new ThreadLocal<Long>();
*/

    public void resolveClassAnnotationBeforeConstruct(ClassResolveContext classResolveContext) throws ResolverException {
        
    }

    public void resolveClassAnnotationAfterConstruct(ClassResolveContext classResolveContext) throws ResolverException {
        
    }

    public void resolveClassAnnotationBeforeMethod(MethodResolveContext methodResolveContext) throws ResolverException {
//        tl.set(System.currentTimeMillis());
        methodResolveContext.setUserData("start_time", System.currentTimeMillis());
    }

    public void resolveClassAnnotationAfterMethod(MethodResolveContext methodResolveContext) throws ResolverException {
/*
        long timeConsumed = System.currentTimeMillis() - tl.get();
        tl.remove();
*/
        long timeConsumed = System.currentTimeMillis() - (Long)methodResolveContext.getUserData("start_time");
        log.info("Executing " + methodResolveContext.getComponentClass().getName() + "." + methodResolveContext.getMethod().getName() + " consume " + timeConsumed + "ms.");
    }

}
